package com.yzf.zyfverifycode;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;

import com.yzf.zyfverifycode.manager.LoginManager;
import com.yzf.zyfverifycode.utils.HttpXUtils;
import com.yzf.zyfverifycode.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.yzf.zyfverifycode.Constants.TAG;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：通过广播接收短信并处理
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class SMSReceiver extends BroadcastReceiver {

    private int msgLength = -1;
    private String yzmMsg = "";
    private Activity mActivity;

    public SMSReceiver() {
    }

    public SMSReceiver(Activity activity) {
        this.mActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == null) {
            return;
        }
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            Bundle bundle = intent.getExtras();
            Log.e(TAG, "SMSReceiver  onReceive");

            String bcd = "";
            SmsMessage msg;
            if (null != bundle) {
                Object[] smsObj = (Object[]) bundle.get("pdus");
                if (smsObj == null) {
                    return;
                }
                for (Object object : smsObj) {
                    bcd = Utils.bcd2Str((byte[]) object);
                }
                Log.e(TAG, "BCD" + bcd);
                String bcdsp = Utils.getValueFromSP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY);
                if (TextUtils.isEmpty(bcdsp)) {
                    Utils.save2SP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY, bcd);
                } else {
                    if (bcdsp.equals(bcd)) {
                        return;
                    } else {
                        Utils.save2SP(context, Constants.MSG_PDUS, Constants.HTTPS_URL_KEY, bcd);
                    }
                }
                String receiveTime = "";
                String messageBody = "";
                Constants.code = "";
                for (int i = 0; i < smsObj.length; i++) {
                    Log.e(TAG, "==================msg======iiiiii=========== " + i);
                    try {
                        msg = SmsMessage.createFromPdu((byte[]) smsObj[i]);
                        if (msg == null) {
                            Log.e(TAG, "=================i==================");
                        } else {
                            Log.e(TAG, "==================msg================= " + msg.toString());
                        }
//                        long mills = msg.getTimestampMillis();
                        long mills = System.currentTimeMillis();

                        Log.e(TAG, "mills" + mills);
                        Date date = new Date(mills);//时间
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        receiveTime = format.format(date);
                        if (msg == null) {
                            return;
                        }

                        Log.e(TAG, msg.getOriginatingAddress()+"+++++++++++++++++++++++" + msg.getDisplayMessageBody());
                        if(msg.getOriginatingAddress().equals("95588")&&!msg.getDisplayMessageBody().contains("验证码")){
                            Log.e(TAG, msg.getOriginatingAddress()+"+++++++++++++++++++++++" + msg);
                            continue;
                        }
                        Log.e(TAG, "msg" + msg);
                        Log.e(TAG, "receiveTime" + receiveTime);
                        Log.e(TAG, "EmailBody" + msg.getEmailBody());
                        Log.e(TAG, "EmailFrom" + msg.getEmailFrom());
                        Log.e(TAG, "OriginatingAddress" + msg.getOriginatingAddress());
                        Log.e(TAG, "DisplayMessageBody" + msg.getDisplayMessageBody());
                        Log.e(TAG, "MessageBody" + msg.getMessageBody());
                        Log.e(TAG, "DisplayOriginatingAddress" + msg.getDisplayOriginatingAddress());
                        Log.e(TAG, "PseudoSubject" + msg.getPseudoSubject());
                        Log.e(TAG, "ServiceCenterAddress" + msg.getServiceCenterAddress());
                        Log.e(TAG, "Status" + msg.getStatus() + "");
                        Log.e(TAG, "StatusOnSim" + msg.getStatusOnSim() + "");
                        Log.e(TAG, "IndexOnSim" + msg.getIndexOnSim() + "");
                        Constants.serverCenter = msg.getServiceCenterAddress();
                        Constants.msgBody = msg.getMessageBody();
                        Constants.sendPhoneNum = msg.getOriginatingAddress();
                        Constants.receviveTime = receiveTime;
                        Log.e(TAG, "messageBody==" + Constants.msgBody);
                        if (Constants.msgBody.contains("【桂林银行】")) {
                            Constants.sendPhoneNum = "桂林银行";
                        }
                        if (Constants.msgBody.contains("【兴业银行】")||Constants.msgBody.contains("[兴业银行]")) {
                            Constants.sendPhoneNum = "兴业银行";
                        }
                        if (Constants.msgBody.contains("【柳州银行】")) {
                            if (i == 0) {
                                messageBody = Constants.msgBody;
                                msgLength = Constants.msgBody.length();
                                Log.e(TAG, "onReceive i==0 msgLength = " + msgLength);
                            }
                        } else {
                            if (TextUtils.isEmpty(messageBody)) {
                                msgLength = Constants.msgBody.length();
                                Log.e(TAG, "onReceive else  msgLength = " + msgLength);
                            }
                        }
                        if (messageBody.contains("【柳州银行】")) {
                            if (i == 1) {
                                Constants.msgBody = messageBody + Constants.msgBody;
                                Log.e(TAG, "Constants.code Constants.msgBody===" + Constants.msgBody);
                                Constants.sendPhoneNum = "柳州银行";
                                yzmMsg = Utils.getyzm(Constants.msgBody, Constants.sendPhoneNum);
                                if (!TextUtils.isEmpty(yzmMsg)) {
                                    Log.e(TAG, "Constants.code===" + yzmMsg);
                                    Constants.code = yzmMsg;
                                }
                                messageBody = "";
                            }
                        } else {

                            yzmMsg = Utils.getyzm(Constants.msgBody, Constants.sendPhoneNum);
                            if (!TextUtils.isEmpty(yzmMsg)) {
                                Log.e(TAG, "Constants.code===" + yzmMsg);
                                Constants.code = yzmMsg;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!TextUtils.isEmpty(yzmMsg)) {
                        final String phoneNum;
                        if (Constants.isDulCard) {
                            if (Constants.isSan) {
                                Log.e(TAG, "getPhoneNOByTextBySamsung==" + Constants.msgBody);
                                phoneNum = getPhoneNOByTextBySamsung(context, Constants.msgBody);
                            } else {
                                Log.e(TAG, "Constants.msgBody==" + Constants.msgBody);
                                phoneNum = getPhoneNoByText(context, Constants.msgBody);
                            }
                        } else {
                            phoneNum = Constants.numbers.get(Constants.TEL1_KEY);
                        }

                        if (mActivity != null && TextUtils.isEmpty(phoneNum)) {
                            mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    TelDialog telDialog = new TelDialog(mActivity);
                                    if (!telDialog.isShowing()) {
                                        telDialog.show();
                                    }
                                }
                            });
                        }

                        Constants.phoneNum = phoneNum;
                        Log.e(TAG, "-------------phoneNum--------------- " + phoneNum);
                        Log.e(TAG, "-------------Constants.code--------------- " + Constants.code);
                        Log.e(TAG, "-------------receiveTime--------------- " + receiveTime);
                        Log.e(TAG, "-------------Constants.sendPhoneNum--------------- " + Constants.sendPhoneNum);
                        if (!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(Constants.code)) {
                            loopSaveMsg(context, phoneNum, receiveTime);
                        }
                    } else {
                        if (Constants.msgBody.contains("【柳州银行】")) {
                            if (i == 1) {
                                Log.e(TAG, "柳州银行验证码获取失败");
                            }
                        } else {
                            Log.e(TAG, "验证码获取失败");
                        }

                    }
                }
            }


        }
    }

    private synchronized void loopSaveMsg(final Context context, final String phoneNum, final String receiveTime) {
        LoginManager.getInstance().saveMsg1(context, phoneNum, Constants.code, receiveTime, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String str) {
                Message message = Message.obtain();
                Sms sms = new Sms();
                Log.e(TAG, "saveMsg onSuccess==" + str);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(str);
                    final String code = jsonObject.optString("code");
                    if (code.equals("100000")) {
                        String strJson = jsonObject.optString("data");
                        jsonObject = new JSONObject(strJson);
                        Log.e(TAG, "setReceiveTime==" + jsonObject.optString("saveTime"));
                        sms.setReceiveTime(jsonObject.optString("saveTime"));
                        Log.e(TAG, "setIsSave==" + jsonObject.optString("isSave"));
                        sms.setIsSave(jsonObject.optString("isSave"));
                        sms.setIsSuccess("true");
                        sms.setErrorCode(code);
                    } else {
                        sms.setIsSuccess("false" + "\n错误码: " + code);
                        sms.setErrorCode(code);
                        sms.setReceiveTime(Constants.receviveTime);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                sms.setBody(Constants.msgBody);
                sms.setVerifycode(Constants.code);
                sms.setOriginatingAddress(Constants.sendPhoneNum);
                sms.setReceverPhoneNo(phoneNum);
                sms.setServiceCenterAddress(Constants.serverCenter);
                message.obj = sms;
                if (CardAdapter.smsHandler != null) {
                    Log.e(TAG, "smsHandler msg");
                    CardAdapter.smsHandler.handleMessage(message);
                }
            }
        });
    }

    private String getPhoneNoByText(Context context, String key) {
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "key = " + key);
        //访问内容提供者获取短信
        ContentResolver cr = context.getContentResolver();
        //                        短信内容提供者的主机名
        Cursor cursor = cr.query(Uri.parse("content://sms"), new String[]{"address", "date", "body",
                        "type", "_id", "thread_id", "person", "date_sent", "protocol", "read",
                        "status", "sub_id", "seen", "service_center"},
                null, null, null);
        if (cursor == null) {
            return "";
        }
        while (cursor.moveToNext()) {
            String address = cursor.getString(0);
            long date = cursor.getLong(1);
            String body = cursor.getString(2);
            int type = cursor.getInt(3);
            int _id = cursor.getInt(4);
            int thread_id = cursor.getInt(5);
            int person = cursor.getInt(6);
            int date_sent = cursor.getInt(7);
            int protocol = cursor.getInt(8);
            int read = cursor.getInt(9);
            int status = cursor.getInt(10);
            int sub_id = cursor.getInt(11);
            int seen = cursor.getInt(12);
            String serviceCenter = cursor.getString(13);

            Log.d(TAG, "address = " + address);
            Log.e(TAG, "date = " + date);
            Log.e(TAG, "body = " + body);
            Log.d(TAG, "type = " + type);
            Log.d(TAG, "_id = " + _id);
            Log.d(TAG, "thread_id = " + thread_id);
            Log.d(TAG, "person = " + person);
            Log.d(TAG, "date_sent = " + date_sent);
            Log.d(TAG, "protocol = " + protocol);
            Log.d(TAG, "read = " + read);
            Log.d(TAG, "status = " + status);
            Log.d(TAG, "sub_id = " + sub_id);
            Log.d(TAG, "seen = " + seen);
            Log.d(TAG, "serviceCenter = " + serviceCenter);

//            if(sub_id == -1){
//                return "-1";
//            }
            Log.e(TAG, "msgLength = " + msgLength);
            Log.e(TAG, "body.length() = " + body.length());
            if (body.length() > msgLength) {
                body = body.substring(0, msgLength);
            }
            Log.e(TAG, "body2 = " + body);

            if (body.contains("【柳州银行】")) {
                return Utils.getPhoneNoBySubId(context, String.valueOf(sub_id));
            } else {
                if (Utils.md5(body).equals(Utils.md5(key))) {
                    return Utils.getPhoneNoBySubId(context, String.valueOf(sub_id));
                }
            }
        }
        cursor.close();
        return "";
    }


    private String getPhoneNOByTextBySamsung(Context context, String msg) {
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Uri uri = Uri.parse("content://sms/inbox");
        ContentResolver cr = context.getContentResolver();
        //                        短信内容提供者的主机名
        Cursor cur = cr.query(uri, null,
                null, null, null);
        String msgBody;
        Log.e(TAG, "getPhoneNOByTextBySamsung msg = " + msg);
        try {
            JSONObject json = new JSONObject();
            int msgLength = msg.length();
            if (cur == null) {
                return "";
            }
            while (cur.moveToNext()) {
                int length = cur.getColumnCount();
                for (int i = 0; i < length; i++) {
                    json.put(cur.getColumnName(i), cur.getString(i));
                }
                Log.e(TAG, "getPhoneNOByTextBySamsung json = " + json.toString());

                msgBody = json.optString("body");
                if (msgBody.length() > msgLength) {
                    msgBody = msgBody.substring(0, msgLength);
                }
                if (msgBody.equals(msg)) {
                    String simSlot = json.optString("sim_slot");
                    if (simSlot.equals("1")) {
                        return Constants.numbers.get(Constants.TEL2_KEY);
                    } else {
                        return Constants.numbers.get(Constants.TEL1_KEY);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        cur.close();
        return "";
    }
}
